package com.example.librarymanagementproject2.Common.utils;

import com.example.librarymanagementproject2.Common.exception.GlobalException;
import org.springframework.web.multipart.MultipartFile;

import java.security.MessageDigest;
import java.util.Base64;

/**
 * @ClassName FileHashUtil
 * @Description TODO
 * @Author Kx
 * @Date 2025/10/27 9:36
 * @Version 1.0
 */
public class FileHashUtil {

    /**
     * @author: kx
     * @date: 2025/10/27 9:38
     * @param file : 文件
     * @return java.lang.String
     * @description: 计算文件的MD5哈希值
    */
    public static String calculateMd5Hash(MultipartFile file) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] fileBytes = file.getBytes();
            byte[] hashBytes = md.digest(fileBytes);
            // 转换为Base64字符串（方便存储和比较）
            return Base64.getEncoder().encodeToString(hashBytes);
        } catch (Exception e) {
            throw new GlobalException(500, "计算文件哈希值失败" + e.getMessage());
        }
    }
}
